package com.cynen.crawler;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * httpGet请求带参数方式测试.
 */

public class HttpGetParamTest {
    public static void main(String[] args) {
        // 基本使用步骤.

        // 1.创建对象.
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 实际需要创建一个带请求参数的uri
        URIBuilder uri = null;
        try {
            uri = new URIBuilder("https://www.baidu.com/s");
            uri.setParameter("wd","Java");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        // 2.创建get请求对象.
        HttpGet httpGet = null;
        try {
            httpGet = new HttpGet(uri.build());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        System.out.println("发起的请求: "+httpGet);

        CloseableHttpResponse httpResponse = null;
        try {
            // 3.使用httpclient发起请求.
            httpResponse = httpClient.execute(httpGet);
            // 4.解析响应.
            if (httpResponse.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(httpResponse.getEntity(),"utf8");
                System.out.println(content);
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 5.关闭资源.
            try {
                // 关闭响应链接
                httpResponse.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                // 关闭客户端.
                httpClient.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
